package com.fankui.serviceedu.controller;


import com.fankui.commonutils.R;
import com.fankui.servicebase.exceptionhandler.LegendaryException;
import com.fankui.serviceedu.client.VodClient;
import com.fankui.serviceedu.entity.EduVideo;
import com.fankui.serviceedu.service.EduVideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author 范奎
 * @since 2023-11-25
 */
@Api(description = "课程小节管理")
@RestController
@RequestMapping("/eduservice/video")
public class EduVideoController {
    @Autowired
    private EduVideoService videoService;

    @Autowired
    private VodClient vodClient;

    @ApiOperation(value = "添加课程小节")
    @PostMapping("addVideo")
    public R addVideo(@ApiParam(name = "video", value = "添加小节对象", required = true) @RequestBody EduVideo video) {
        boolean flag = videoService.save(video);
        if (flag) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @ApiOperation(value = "根据小节id查询小节信息")
    @GetMapping("getVideoById/{videoId}")
    public R getVideoById(@ApiParam(name = "videoId", value = "小节id", required = true) @PathVariable String videoId) {
        EduVideo video = videoService.getById(videoId);
        return R.ok().data("video", video);
    }

    @ApiOperation(value = "修改课程小节")
    @PostMapping("updateVideo")
    public R updateVideo(@ApiParam(name = "video", value = "修改小节对象", required = true) @RequestBody EduVideo video) {
        boolean flag = videoService.updateById(video);
        if (flag) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @ApiOperation(value = "根据小节id删除小节信息")
    @DeleteMapping("remove/{videoId}")
    public R removeVideo(@ApiParam(name = "videoId", value = "小节id", required = true) @PathVariable String videoId) {
        EduVideo video = videoService.getById(videoId);
        String videoSourceId = video.getVideoSourceId();
        if (!StringUtils.isEmpty(videoSourceId)) {
            // 远程调用视频删除接口删除小节对应的视频
            R result = vodClient.removeVodVideo(videoSourceId);
            if (result.getCode() != 20000) {
                throw new LegendaryException(20001, "删除小节失败！");
            }
        }
        boolean flag = videoService.removeById(videoId);
        if (flag) {
            return R.ok();
        } else {
            return R.error();
        }
    }
}

